package com.trade.module.base.controller;

import com.trade.module.base.entity.User;
import com.trade.module.base.service.UserService;
import com.trade.common.utils.BeanUtil;
import com.trade.common.utils.Constants;
import com.trade.common.utils.XaUtil;
import com.trade.module.base.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.support.WebApplicationObjectSupport;

/**
 * Class Description:基础控制类
 *
 * @Version v1.0 2017/4/22 17:50
 * @JDK version 1.8.0_51
 * @Author zfb
 */
public class BaseController extends WebApplicationObjectSupport {
    /**
     * 日志类型声明
     **/
    public static final Logger logs = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户对象
     *
     * @return UserVo 用户vo对象
     */
    public UserVo getCurrentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userAccount = "";
        if (principal instanceof String) {
            userAccount = principal.toString();
        } else if (principal instanceof UserDetails) {
            userAccount = ((UserDetails) principal).getUsername();
        }
        User user = null;
        if (XaUtil.isNotEmpty(userAccount)) {
            user = userService.findByAccountAndUserFlagAndDataFlag(userAccount,
                    Constants.USER_FLAG_USERED, Constants.DATA_FLAG_OK);
        }
        //如果查询出来的用户信息存在，则将用户信息转换为VO对象并返回，用户密码必须设置为空字符串
        UserVo currentUserVo = new UserVo();
        if (null != user) {
            try {
                BeanUtil.copyAllProperties(user, currentUserVo);
                currentUserVo.setPassWord("");
            } catch (Exception e) {
                logs.error("登录用户信息查询转化异常，用户名：" + user.getAccount());
                e.printStackTrace();
            }
            return currentUserVo;
        } else {
            return null;
        }
    }

    /**
     * 获得当前用户的id，如果登录用户获取失败，返回""
     *
     * @return id
     */
    public String getCurrentUserId() {
        UserVo currentUserVo = getCurrentUser();
        return (currentUserVo != null) ? currentUserVo.getId() : "";
    }
}
